package com.pri.chat.activity;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DetailListBean;
import com.netease.nim.uikit.net.entity.InviteBean;
import com.netease.nim.uikit.net.entity.InviteInfoBean;
import com.netease.nim.uikit.net.entity.TiXianBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.DetailAdapter;
import com.pri.chat.adapter.InviteAdapter;
import com.pri.chat.adapter.TiXianBeanAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.ConfirmTxModel;
import com.pri.chat.utils.ClipBoardUtil;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.view.AutoVerticalScrollTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 愿望金记录
 */
public class InviteActivity extends BaseActivity {
    @BindView(R.id.backImageBtn)
    ImageView backImageBtn;

    @BindView(R.id.tishiTv)
    AutoVerticalScrollTextView tishiTv;
    @BindView(R.id.guizeBtn)
    ImageView guizeBtn;
    @BindView(R.id.yqsyTextView)
    TextView yqsyTextView;
    @BindView(R.id.yqmTextView)
    TextView yqmTextView;
    @BindView(R.id.fuzhiBtn)
    TextView fuzhiBtn;
    @BindView(R.id.yqhyslNum)
    TextView yqhyslNum;
    @BindView(R.id.inviteBtn)
    View inviteBtn;

    @BindView(R.id.huodongTime)
    TextView huodongTime;
    @BindView(R.id.canyufangshi)
    TextView canyufangshi;

    @BindView(R.id.wdjlTextView)
    TextView wdjlTextView;
    @BindView(R.id.ljtxBtn)
    TextView ljtxBtn;
    @BindView(R.id.yqcgNum)
    TextView yqcgNum;
    @BindView(R.id.yqrwxNum)
    TextView yqrwxNum;

    @BindView(R.id.guizeFrame)
    FrameLayout guizeFrame;
    @BindView(R.id.huodongTextView)
    TextView huodongTextView;
    @BindView(R.id.wzdleBtn)
    TextView wzdleBtn;

    @BindView(R.id.txjlTv)
    TextView txjlTv;
    @BindView(R.id.tishiTextView)
    TextView tishiTextView;


    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.tixianRelation)
    View tixianRelation;
    @BindView(R.id.tixianZheCeng)
    View tixianZheCeng;






    @BindView(R.id.rec_recharge_list)
    RecyclerView recRechargeList;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    private int page = 1;

    private int number;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 199) {
                tishiTv.next();
                number++;
                tishiTv.setText(msgList.get(number % msgList.size()));
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_invite_layout;
    }

    private String[] bStr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"};

    private List<String> msgList = new ArrayList<>();
    @Override
    protected void initView() {
        rl_center.setVisibility(View.GONE);
        huodongTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
        yqmTextView.setText(SharedHelper.readNimId(mContext));

        tishiTv.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView tv = new TextView(mContext);
                tv.setTextSize(13);
                tv.setTextColor(getResources().getColor(R.color.lunbomsg));
                tv.setSingleLine(true);
                tv.setEllipsize(TextUtils.TruncateAt.END);
                tv.setGravity(Gravity.CENTER_VERTICAL);
                return tv;
            }
        });

        initRv();
        initRv1();
        initSrl();
    }


    private List<TiXianBean> mList1;
    private TiXianBeanAdapter mAdapter1;
    private int mPosition = -1;

    private void initRv1() {
        mList1 = new ArrayList<>();
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 3);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter1 = new TiXianBeanAdapter(R.layout.item_tixian, mList1);
        recMain.setAdapter(mAdapter1);
        mAdapter1.setOnItemClickListener((adapter, view, position) -> {
            httpTX(mList1.get(position).getMoney());
            tixianRelation.setVisibility(View.GONE);
        });
    }

    private boolean isThreadRunning = false;
    private void notice() {
        new Thread() {
            @Override
            public void run() {
                while (isThreadRunning) {
                    handler.sendEmptyMessage(199);
                    SystemClock.sleep(3000);
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        isThreadRunning = false;
        super.onDestroy();
    }

    private List<InviteBean> mList = new ArrayList<>();
    private InviteAdapter mAdapter;
    private void initRv() {
        LinearLayoutManager linearLayoutManager =new LinearLayoutManager(this);
        recRechargeList.setLayoutManager(linearLayoutManager);
        recRechargeList.setNestedScrollingEnabled(false);
        mAdapter=new InviteAdapter(R.layout.item_invite, mList);
        recRechargeList.setAdapter(mAdapter);
    }

    private void initSrl() {
        srlAll.setEnableRefresh(false);
        srlAll.setEnableLoadmore(false);
        srlAll.setEnableAutoLoadmore(false);
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            page++;
            getYqjlList();
        });
    }

    private void refresh() {
        page=1;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        srlAll.setEnableLoadmore(true);
        getYqjlList();
    }

    @Override
    protected void initData() {
        getyqInfo();
        getYqjlList();
    }

    private String yqsyMoney;
    private String msg;
    private void getyqInfo(){
        SubscriberOnNextListener<BaseBean<InviteInfoBean>> onNextListener = baseBean -> {
            msg = baseBean.getData().getMsg();
            yqsyMoney = baseBean.getData().getYqsyMoney();
            yqsyTextView.setText(baseBean.getData().getYqsyMoney()+"元");
            yqhyslNum.setText(baseBean.getData().getDyyqrTotalNum());
            huodongTime.setText("活动时间："+baseBean.getData().getHuoDongTime());
            canyufangshi.setText(Html.fromHtml("参与方式："+baseBean.getData().getYqcgdedaoMoney()));
            wdjlTextView.setText(baseBean.getData().getYqsyMoney()+"元");
            yqcgNum.setText(baseBean.getData().getDyyqcgNum());
            yqrwxNum.setText(baseBean.getData().getDyyqwxNum());
            huodongTextView.setText(Html.fromHtml(baseBean.getData().getGuize()));
            if("1".equals(baseBean.getData().getShowLunBo())){
                int price = Integer.parseInt(baseBean.getData().getYqcgdedaoMoney());
                String tishiMessage = "";
                for(int i=0;i<5;i++){
                    msgList.add("****"+getRandomJianHan(1)+"，邀请了"+(20+i*2)+"位好友，已经提现了 "+(((20+i*2))*price)+" 元！");
                }
                isThreadRunning = true;
                notice();
            }


            mList1.clear();
            mList1.addAll(baseBean.getData().getTiXianBeanList());
            mAdapter1.notifyDataSetChanged();
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getInviteInfo(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    //自动生成名字（中文）
    public static String getRandomJianHan(int len) {
        String ret = "";
        for (int i = 0; i < len; i++) {
            String str = null;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBK"); // 转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret += str;
        }
        return ret;
    }

    private void getYqjlList(){
        SubscriberOnNextListener<BaseBean<List<InviteBean>>> onNextListener = baseBean -> {
            mList.addAll(baseBean.getData());
            mAdapter.notifyDataSetChanged();
            if(baseBean.getData().size()<10){
                srlAll.setEnableLoadmore(false);
            }
            if(mList.size() > 0){
                tishiTextView.setVisibility(View.GONE);
            }
        };
        Map<String,Object> params = new HashMap<>();//登录上传参数
        params.put("memberId",SharedHelper.readId(this));
        params.put("pageIndex",page+"");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().listInviteList(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    @OnClick({R.id.tixianZheCeng,R.id.backImageBtn,R.id.ljtxBtn,R.id.guizeBtn,R.id.wzdleBtn,R.id.inviteBtn,R.id.txjlTv,R.id.fuzhiBtn,R.id.yqmTextView})
    public void onViewClicked(View view) {

        if(view.getId() == R.id.tixianZheCeng){
            tixianRelation.setVisibility(View.GONE);
        } else if(view.getId() == R.id.backImageBtn){
            finish();
        } else if(view.getId() == R.id.guizeBtn){
            guizeFrame.setVisibility(View.VISIBLE);
        }else if(view.getId() == R.id.inviteBtn){
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setText("#快来领新人福利,点击【http://www.nbninikeji.com/downApk.client?userCode="+SharedHelper.readNimId(mContext)+"】下载萤火APP，填写我的邀请码【"+SharedHelper.readNimId(mContext)+"】，红包提现立马到");
            initShareDialog();
        }else if(view.getId() == R.id.wzdleBtn){
            guizeFrame.setVisibility(View.GONE);
        }else if(view.getId() == R.id.txjlTv){
            Bundle bundle = new Bundle();
            bundle.putInt("type",4);
            RxActivityTool.skipActivity(mContext,MoneyNoteListActivity.class,bundle);
        }else if(view.getId() == R.id.fuzhiBtn || view.getId() == R.id.yqmTextView){
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setText("#快来领新人福利,点击【http://www.nbninikeji.com/downApk.client?userCode="+SharedHelper.readNimId(mContext)+"】下载萤火APP，填写我的邀请码【"+SharedHelper.readNimId(mContext)+"】，红包提现立马到");
            RxToast.normal("复制成功，赶紧去分享吧！");
        }else if(view.getId() == R.id.ljtxBtn){
//            if("0".equals(yqhyslNum.getText().toString())){
//                RxToast.normal("您还未邀请好友");
//                return;
//            }
            if(!StringUtils.isEmpty(msg)){
                RxToast.normal(msg);
                return;
            }
            tixianRelation.setVisibility(View.VISIBLE);
            //提现
//            httpTX();
        }
    }


    private Dialog mShareDialog;
    private void initShareDialog() {
        mShareDialog= DialogUtil.getInstance().showShareDialog(this,5);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {

            }

            @Override
            public void circleOnClick(View v) {
                if(StringUtils.isEmpty(ClipBoardUtil.paste(mContext))){
                    RxToast.normal("请先去点击复制您的邀请码！");
                    return;
                }
                DialogUtil.getInstance().shareWechatMoments("http://nbninikeji.com/202010271048341603766914940.png",HttpMethods.SHARE_TITLE,"邀请用户",HttpMethods.SHARE_URL);
                mShareDialog.dismiss();
            }

            @Override
            public void qZoneOnClick(View v) {
            }

            @Override
            public void weixinOnClick(View v) {
                DialogUtil.getInstance().shareWeChat("http://nbninikeji.com/202010271048341603766914940.png",HttpMethods.SHARE_TITLE,"#快来领新人福利\n" +
                        "点击【http://www.nbninikeji.com/downApk.client?userCode="+SharedHelper.readNimId(mContext)+"】下载萤火APP\n" +
                        "    填我邀请码【"+SharedHelper.readNimId(mContext)+"】\n" +
                        "红包提现立马到",HttpMethods.SHARE_URL);
                mShareDialog.dismiss();
            }

            @Override
            public void jubaoOnClick(View v) {

            }
        });
        mShareDialog.show();
    }


    private void httpTX(String money) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            initData();
        };
        ConfirmTxModel regModel = new ConfirmTxModel();//登录上传参数
        regModel.setMemberId(SharedHelper.readId(this));
        regModel.setTxMoney(money);
        regModel.setTxType(4);
        regModel.setType(0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(regModel));
        HttpMethods.getInstance().tiXian(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
